package com.WOWTradeNews.services;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpConnection;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.WOWTradeNews.Utils;
import com.WOWTradeNews.DataBase.Country;
import com.WOWTradeNews.DataBase.News;

import android.R.integer;
import android.graphics.Bitmap;
import android.util.Log;
import android.widget.ArrayAdapter;



/**
 * 
 * @author zhaosdfa
 *
 */
public class NewsServer {
	//base path
	private static final String BASE_PATH     = "http://www.mi-great.com.tw/wow/json/json_news.asp?theme=";
	//市調菁華
	private static final String MARKET_PATH   = "http://www.mi-great.com.tw/wow/json/json_news.asp?theme=2";
	//專題研析
	private static final String SPECIAL_PATH  = "http://www.mi-great.com.tw/wow/json/json_news.asp?theme=3"; 
	//商情放送
	private static final String TRADE_PATH    = "http://www.mi-great.com.tw/wow/json/json_news.asp?theme=4";
	//活動快訊
	private static final String ACTIVITY_PATH = "http://www.mi-great.com.tw/wow/json/json_news.asp?theme=5";
	//經貿書訊
	private static final String BOOK_PATH     = "http://www.mi-great.com.tw/wow/json/json_book.asp?theme=6";
	
	private static final String COUNTRY_PATH  = "http://www.mi-great.com.tw/wow/json/json_form.asp?theme=9&xid=";
	
	private static final String SEARCH_BASE_PATH = "http://www.mi-great.com.tw/wow/json/json_searchnews.asp?";
	
	//theme=&keywords=&country=&city=&date1=&date2=&search=yes s_keywords
	private static final String[] SEARCH_VALUES  = {
		"theme", "keywords", "s_keywords", "country", "city" ,"date1", "date2", "search"
	};
	
	/**
	 * 
	 * @param type
	 * @return
	 * @throws Exception
	 */
	public static List<News> getNewsList(int type) throws Exception {
		List<News> list = new ArrayList<News>();
		URL url = null;
		if(type == 5) {
			url = new URL("http://www.mi-great.com.tw/wow/json/json_acts.asp?theme=" + type);
		} else {
			url = new URL(BASE_PATH + type);
		}
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setConnectTimeout(50000);
		conn.setRequestMethod("GET");
		
		if(conn.getResponseCode() == 200) {
			list = paressJson(conn.getInputStream(), type);
		}
		
		return list;
	}
	
	/**
	 * 
	 * @param inputStream
	 * @return
	 * @throws Exception
	 */
	private static List<News> paressJson(InputStream inputStream, int type) throws Exception {
		List<News> list = new ArrayList<News>();
		
		byte[] data = Utils.readInputStream(inputStream);
		String json = new String(data);
		JSONObject jsonObject = new JSONObject(json);
		
		Log.d("zhaosdfa", "data---->>>Json" + json);
		
		int total = Integer.valueOf(jsonObject.getString("total"));
		Log.d("zhaosdfa", "total:" + total);
		JSONArray jsonArray = jsonObject.getJSONArray("data");
		for(int i=0; i<jsonArray.length(); i++) {
			JSONObject job = jsonArray.getJSONObject(i);
			//news
			//iid subject contents sid datein down_date author intPublish country city news_link keywords
			//date_build is_post img1
			News news = new News();
			news.setNewsType(type);
			news.setIid(job.getString("iid"));
			news.setSubject(job.getString("subject"));
			news.setContents(job.getString("contents"));
			news.setSid(job.getString("sid"));
			news.setDatein(job.getString("datein"));
			news.setDown_date(job.getString("down_date"));
			news.setAuthor(job.getString("author"));
			news.setActtime(job.optString("acttime"));
			news.setActive(job.optString("active"));
			try {
				news.setIntPublish(job.getString("intPublish"));
			} catch (Exception e) {
				news.setIntPublish("");
			}
			news.setCountry(job.getString("country"));
			news.setCity(job.getString("city"));
			news.setNews_link(job.getString("news_link"));
			try {
				news.setKeyWords(job.getString("words"));
			} catch (Exception e) {
				news.setKeyWords("");
			}
			news.setDate_build(job.getString("date_build"));
			try {
				news.setIs_post(job.getString("is_post").equals("False") ? false : true);
			} catch (Exception e) {
				news.setIs_post(false);
			}
			
			try {
				news.setImg1Url(job.getString("img1"));
				news.setTxt1Url("");
			} catch (Exception e) {
				news.setImg1Url("");
				news.setTxt1Url(job.getString("txt1"));
			}
			
			try {
				news.setImg2Url(job.optString("img2"));
			} catch(Exception e) {
				news.setImg2Url("");
			}
			
			try {
				news.setImg3Url(job.optString("img3"));
			} catch(Exception e) {
				news.setImg3Url("");
			}
			
			list.add(news);
			//Log.d("zhaosdfa", news.getSubject());
		}
		
		return list;
	}
	
	private static Map<String, String> paressJson2(InputStream inputStream) throws Exception {
		Map<String, String> map = new HashMap<String, String>();
		byte[] data = Utils.readInputStream(inputStream);
		
		String json = new String(data);
		//Log.d("zhaosdfa", "map---->>>>" + json);
		
		JSONArray jsonArray = new JSONArray(json);
		for(int i=0; i<jsonArray.length(); i++) {
			JSONObject job = jsonArray.getJSONObject(i);
			int iid = job.getInt("iid");
			String country = job.getString("title");
			map.put(country, String.valueOf(iid));
		}
		
		return map;
	}
	
	public static Map<String, String> getCountryMap() throws Exception {
		Map<String, String> map = null;
		String urlString = "http://www.mi-great.com.tw/wow/json/json_country.asp?theme=9";
		URL url = new URL(urlString);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setConnectTimeout(50000);
		conn.setRequestMethod("GET");
		
		if(conn.getResponseCode() == 200) {
			map = paressJson2(conn.getInputStream());
		}
		
		return map;
	}
	
	public static List<Country> getCountries(String xid) throws Exception{
		List<Country> list = new ArrayList<Country>();
		URL url = new URL(COUNTRY_PATH + xid);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setConnectTimeout(50000);
		conn.setRequestMethod("GET");
		
		if(conn.getResponseCode() == 200) {
			list = paressJson3(conn.getInputStream());
		}
		
		return list;
	}
	
	public static List<Country> getCT(String cy) throws Exception{
		List<Country> list = new ArrayList<Country>();
		URL url = new URL("http://www.mi-great.com.tw/wow/json/json_word.asp?words=" + URLEncoder.encode(cy));
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setConnectTimeout(50000);
		conn.setRequestMethod("GET");
		
		if(conn.getResponseCode() == 200) {
			list = paressJson3(conn.getInputStream());
		}
		
		return list;
	}
	
	private static List<Country> paressJson3(InputStream inputStream) throws Exception {
		List<Country> list = new ArrayList<Country>();
		byte[] data = Utils.readInputStream(inputStream);
		String json = new String(data);
		
		JSONArray jsonArray = new JSONArray(json);
		for(int i=0; i<jsonArray.length(); i++) {
			JSONObject job = jsonArray.getJSONObject(i);
			Country cty = new Country();
			cty.setIid(job.getString("iid"));
			cty.setName(job.getString("title"));
			cty.setContents(job.getString("content"));
			list.add(cty);
		}
		
		return list;
	}
	
	public static List<News> searchList(Map<String, String> map) throws Exception{
		List<News> list = new ArrayList<News>();
		
		//www.mi-great.com.tw/wow/json/json_searchnews.asp?
		//theme=&keywords=&country=&city=&date1=&date2=&search=yes
		
		StringBuilder builder = new StringBuilder(SEARCH_BASE_PATH);
		for(String t : SEARCH_VALUES) {
			builder.append(t).append("=");
			builder.append(map.get(t)).append("&");
		}
		builder.deleteCharAt(builder.length()-1);
		
		String surl = builder.toString();
		Log.d("zhaosdfa", surl);
		
		URL url1 = new URL(surl);
		HttpURLConnection conn = (HttpURLConnection) url1.openConnection();
		conn.setConnectTimeout(50000);
		conn.setRequestMethod("GET");
		
		//byte[] data = Utils.readInputStream(conn.getInputStream());
		//String json = new String(data);
		//Log.d("zhaosdfa", "map--->" + json);
		
		if(conn.getResponseCode() == 200) {
			list = paressJson(conn.getInputStream(), 1);
		}
		
		return list;
	}
	
	public static List<Country> getCountriesList() throws Exception{
		List<Country> list = null;
		String urlString = "http://www.mi-great.com.tw/wow/json/json_country.asp?theme=9";
		URL url = new URL(urlString);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setConnectTimeout(50000);
		conn.setRequestMethod("GET");
		
		if(conn.getResponseCode() == 200) {
			list = paressJson4(conn.getInputStream());
		}
		return list;
	}

	private static List<Country> paressJson4(InputStream inputStream) throws Exception {
		List<Country> list = new ArrayList<Country>();
		byte[] data = Utils.readInputStream(inputStream);
		
		String json = new String(data);
		//Log.d("zhaosdfa", "map---->>>>" + json);
		
		JSONArray jsonArray = new JSONArray(json);
		for(int i=0; i<jsonArray.length(); i++) {
			JSONObject job = jsonArray.getJSONObject(i);
			int iid = job.getInt("iid");
			String country = job.getString("title");
			//map.put(country, String.valueOf(iid));
			Country c = new Country();
			c.setIid(String.valueOf(iid));
			c.setName(country);
			list.add(c);
		}
		return list;
	}
	
}






